package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Transactional
    @Override
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 1.保存菜品基本信息
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insert(dish);

        // 2.保存菜品口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
        // 删除redis缓存中的菜品数据
        redisTemplate.delete("dish:cache:"+dishDTO.getCategoryId());
        log.info("新增菜品，清理缓存的菜品");

    }

    @Override
    public Category selectById(Long id) {
        Category category = dishMapper.selectById(id);
        return category;
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        // 1.设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        // 2.执行查询
        List<DishVO> dishVOList = dishMapper.pageQuery(dishPageQueryDTO);

        // 3.解析并封装分页结果
        Page<DishVO> page = (Page<DishVO>) dishVOList;

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Transactional
    @Override
    public void delete(List<Long> ids) {
        // 1.判断菜品的状态，启售的菜品不能删除，提示错误信息
        Long count = dishMapper.countEnableDishByIds(ids);
        if (count > 0){
            throw new BaseException(MessageConstant.DISH_ON_SALE);
        }
        // 2.判断菜品是否关联套餐，如果关联套餐，不能删除，提示错误信息
        List<Long> setmealIds =  setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (!CollectionUtils.isEmpty(setmealIds)){  // 关联了套餐
            throw new BaseException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 3.删除菜品，并删除菜品口味
        dishMapper.deleteByIds(ids);
        // 删除菜品口味
        dishFlavorMapper.deleteDishFlavorByDishIds(ids);

        // 删除redis缓存中的菜品数据
        Set<Object> keys = redisTemplate.keys("dish:cache:*");
        redisTemplate.delete(keys);

    }

    @Override
    public DishVO getInfo(Long id) {
        // 1.根据Id查询菜品的基本信息 - Dish
        Dish dish = dishMapper.getById(id);


        // 2.根据Id查询菜品口味列表信息 - List<DishFlavor>
        List<DishFlavor> flavorList = dishFlavorMapper.getByDishId(id);

        // 3.组装数据
        DishVO dishVO = new DishVO();
        if (!(dish == null)){
            BeanUtils.copyProperties(dish,dishVO);
        }
        dishVO.setFlavors(flavorList);

        return dishVO;
    }

    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        // 1.根据Id修改菜品的基本信息 -- dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);

        // 2.根据菜品id修改菜品口味信息 -- dish_flavor (先删 后加)
        // 2.1 根据菜品id删除口味数据
        dishFlavorMapper.deleteDishFlavorByDishIds(Collections.singletonList(dish.getId()));

        // 2.2 在添加
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

        // 删除redis缓存中的菜品数据
        Set<Object> keys = redisTemplate.keys("dish:cache:*");
        redisTemplate.delete(keys);

    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        // 根据分类id查询菜品，并且是启用状态的菜品
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();
        // 将每一个菜品数据拷贝给DishVo并且封装每一个菜品的口味数据给DishVo
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


    @Override
    public List<DishVO> listDishWithFlavors(Long categoryId) {
        String redisDishKey = "dish:cache:"+categoryId;
        // 1.先查询redis缓存,如果缓存中有数据，直接返回
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(redisDishKey);
        if (!CollectionUtils.isEmpty(dishVOList)){
            log.info("查询redis缓存，直接返回");
            return dishVOList;
        }

        // 2.如果缓存中没有数据，在查询数据库
        Dish dish = Dish.builder().categoryId(categoryId).status(StatusConstant.ENABLE).build();
        dishVOList = dishMapper.listDishWithFlavors(dish);


        // 3.把数据库查询的结果，加入缓存
        redisTemplate.opsForValue().set(redisDishKey,dishVOList);
        log.info("查询数据库，查询到的数据，缓存在redis");

        return dishVOList;
    }
}
